import Clipboard from 'clipboard'
import JSEncrypt from "jsencrypt";

export function isNull(value) {
  return (value === null) || (value === undefined);
}

export function isNotNull(value) {
  return (value !== null) && (value !== undefined);
}

export function isEmptyStr(str) {
  //return (str === undefined) || (!str) || (!/[^\s]/.test(str));
  return (str === undefined) || (!str && (str !== 0) && (str !== '0')) || (!/[^\s]/.test(str));
}

export const generateId = function() {
  return Math.floor(Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000);
};

export const deepClone = function (origin) {
  if (origin === undefined) {
    return undefined
  }
  return JSON.parse(JSON.stringify(origin))
}

export const overwriteObj = function(obj1, obj2) {  /* 浅拷贝对象属性，obj2覆盖obj1 */
  // for (let prop in obj2) {
  //   if (obj2.hasOwnProperty(prop)) {
  //     obj1[prop] = obj2[prop]
  //   }
  // }

  Object.keys(obj2).forEach(prop => {
    obj1[prop] = obj2[prop]
  })
}

export const addWindowResizeHandler = function (handler) {
  let oldHandler = window.onresize
  if (typeof window.onresize != 'function') {
    window.onresize = handler
  } else {
    window.onresize = function () {
      oldHandler()
      handler()
    }
  }
}

const createStyleSheet = function() {
  let head = document.head || document.getElementsByTagName('head')[0];
  let style = document.createElement('style');
  style.type = 'text/css';
  head.appendChild(style);
  return style.sheet;
}

export const insertCustomCssToHead = function (cssCode, formId = '') {
  let head = document.getElementsByTagName('head')[0]
  let oldStyle = document.getElementById('vform-custom-css')
  if (oldStyle) {
    head.removeChild(oldStyle)  //先清除后插入！！
  }
  if (formId) {
    oldStyle = document.getElementById('vform-custom-css' + '-' + formId)
    !!oldStyle && head.removeChild(oldStyle)  //先清除后插入！！
  }

  let newStyle = document.createElement('style')
  newStyle.type = 'text/css'
  newStyle.rel = 'stylesheet'
  newStyle.id = formId ? 'vform-custom-css' + '-' + formId : 'vform-custom-css'
  try {
    newStyle.appendChild(document.createTextNode(cssCode))
  } catch(ex) {
    newStyle.styleSheet.cssText = cssCode
  }

  head.appendChild(newStyle)
}

export const insertGlobalFunctionsToHtml = function (functionsCode, formId = '') {
  let bodyEle = document.getElementsByTagName('body')[0]
  let oldScriptEle = document.getElementById('v_form_global_functions')
  !!oldScriptEle && bodyEle.removeChild(oldScriptEle)  //先清除后插入！！
  if (formId) {
    oldScriptEle = document.getElementById('v_form_global_functions' + '-' + formId)
    !!oldScriptEle && bodyEle.removeChild(oldScriptEle)  //先清除后插入！！
  }

  let newScriptEle = document.createElement('script')
  newScriptEle.id = formId ? 'v_form_global_functions' + '-' + formId : 'v_form_global_functions'
  newScriptEle.type = 'text/javascript'
  newScriptEle.innerHTML = functionsCode
  bodyEle.appendChild(newScriptEle)
}

export const optionExists = function(optionsObj, optionName) {
  if (!optionsObj) {
    return false
  }

  return Object.keys(optionsObj).indexOf(optionName) > -1
}

export const loadRemoteScript = function(srcPath, callback) {  /*加载远程js，加载成功后执行回调函数*/
  let sid = encodeURIComponent(srcPath)
  let oldScriptEle = document.getElementById(sid)

  if (!oldScriptEle) {
    let s = document.createElement('script')
    s.src = srcPath
    s.id = sid
    document.body.appendChild(s)

    s.onload = s.onreadystatechange = function (_, isAbort) { /* 借鉴自ace.js */
      if (isAbort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
        s = s.onload = s.onreadystatechange = null
        if (!isAbort) {
          callback()
        }
      }
    }
  }
}

export function traverseFieldWidgets(widgetList, handler, parent = null) {
  widgetList.map(w => {
    if (w.formItemFlag) {
      handler(w, parent)
    } else if (w.type === 'grid') {
      w.cols.map(col => {
        traverseFieldWidgets(col.widgetList, handler, w)
      })
    } else if (w.type === 'table') {
      w.rows.map(row => {
        row.cols.map(cell => {
          traverseFieldWidgets(cell.widgetList, handler, w)
        })
      })
    } else if (w.type === 'tab') {
      w.tabs.map(tab => {
        traverseFieldWidgets(tab.widgetList, handler, w)
      })
    } else if (w.type === 'sub-form') {
      traverseFieldWidgets(w.widgetList, handler, w)
    } else if (w.category === 'container') {  //自定义容器
      traverseFieldWidgets(w.widgetList, handler, w)
    }
  })
}

export function traverseContainerWidgets(widgetList, handler) {
  widgetList.map(w => {
    if (w.category === 'container') {
      handler(w)
    }

    if (w.type === 'grid') {
      w.cols.map(col => {
        traverseContainerWidgets(col.widgetList, handler)
      })
    } else if (w.type === 'table') {
      w.rows.map(row => {
        row.cols.map(cell => {
          traverseContainerWidgets(cell.widgetList, handler)
        })
      })
    } else if (w.type === 'tab') {
      w.tabs.map(tab => {
        traverseContainerWidgets(tab.widgetList, handler)
      })
    } else if (w.type === 'sub-form') {
      traverseContainerWidgets(w.widgetList, handler)
    } else if (w.category === 'container') {  //自定义容器
      traverseContainerWidgets(w.widgetList, handler)
    }
  })
}

export function traverseAllWidgets(widgetList, handler) {
  widgetList.map(w => {
    handler(w)

    if (w.type === 'grid') {
      w.cols.map(col => {
        handler(col)
        traverseAllWidgets(col.widgetList, handler)
      })
    } else if (w.type === 'table') {
      w.rows.map(row => {
        row.cols.map(cell => {
          handler(cell)
          traverseAllWidgets(cell.widgetList, handler)
        })
      })
    } else if (w.type === 'tab') {
      w.tabs.map(tab => {
        traverseAllWidgets(tab.widgetList, handler)
      })
    } else if (w.type === 'sub-form') {
      traverseAllWidgets(w.widgetList, handler)
    } else if (w.category === 'container') {  //自定义容器
      traverseAllWidgets(w.widgetList, handler)
    }
  })
}

function handleWidgetForTraverse(widget, handler) {
  if (widget.category) {
    traverseFieldWidgetsOfContainer(widget, handler)
  } else if (widget.formItemFlag) {
    handler(widget)
  }
}

/**
 * 遍历容器内的字段组件
 * @param con
 * @param handler
 */
export function traverseFieldWidgetsOfContainer(con, handler) {
  if (con.type === 'grid') {
    con.cols.forEach(col => {
      col.widgetList.forEach(cw => {
        handleWidgetForTraverse(cw, handler)
      })
    })
  } else if (con.type === 'table') {
    con.rows.forEach(row => {
      row.cols.forEach(cell => {
        cell.widgetList.forEach(cw => {
          handleWidgetForTraverse(cw, handler)
        })
      })
    })
  } else if (con.type === 'tab') {
    con.tabs.forEach(tab => {
      tab.widgetList.forEach(cw => {
        handleWidgetForTraverse(cw, handler)
      })
    })
  } else if (con.type === 'sub-form') {
    con.widgetList.forEach(cw => {
      handleWidgetForTraverse(cw, handler)
    })
  } else if (con.category === 'container') {  //自定义容器
    con.widgetList.forEach(cw => {
      handleWidgetForTraverse(cw, handler)
    })
  }
}

/**
 * 获取所有字段组件
 * @param widgetList
 * @returns {[]}
 */
export function getAllFieldWidgets(widgetList) {
  let result = []
  let handlerFn = (w) => {
    result.push({
      type: w.type,
      name: w.options.name,
      field: w
    })
  }
  traverseFieldWidgets(widgetList, handlerFn)

  return result
}

/**
 * 获取所有容器组件
 * @param widgetList
 * @returns {[]}
 */
export function getAllContainerWidgets(widgetList) {
  let result = []
  let handlerFn = (w) => {
    result.push({
      type: w.type,
      name: w.options.name,
      container: w
    })
  }
  traverseContainerWidgets(widgetList, handlerFn)

  return result
}

export function copyToClipboard(content, clickEvent, $message, successMsg, errorMsg) {
  const clipboard = new Clipboard(clickEvent.target, {
    text: () => content
  })

  clipboard.on('success', () => {
    $message.success(successMsg)
    clipboard.destroy()
  })

  clipboard.on('error', () => {
    $message.error(errorMsg)
    clipboard.destroy()
  })

  clipboard.onClick(clickEvent)
}

export function getQueryParam(variable) {
  let query = window.location.search.substring(1);
  let vars = query.split("&")
  for (let i=0; i<vars.length; i++) {
    let pair = vars[i].split("=")
    if(pair[0] == variable) {
      return pair[1]
    }
  }

  return undefined;
}

export function getDefaultFormConfig() {
  return {
    modelName: 'formData',
    refName: 'vForm',
    rulesName: 'rules',
    labelWidth: 80,
    labelPosition: 'left',
    size: '',
    labelAlign: 'label-left-align',
    cssCode: '',
    customClass: '',
    functions: '',  //全局函数
    layoutType: 'PC',
    jsonVersion: 3,

    onFormCreated: '',
    onFormMounted: '',
    onFormDataChange: '',
  }
}

export function buildDefaultFormJson() {
  return {
    widgetList: [],
    formConfig: deepClone( getDefaultFormConfig() )
  }
}

export const isMobile = function() {
	let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
	if (flag) {
		//Mobile
		return true;
	} else {
		//Pc
		return false;
	}
}
/**
 * 判断GPS坐标在不在指定的参考范围内
 * @param latitude
 * @param longitude
 * @param clat
 * @param clon
 * @param dis
 * @returns {{res: boolean, distance: number}}
 */
export const calculateDistance = function (latitude,longitude,clat,clon,dis) {
	if(dis==undefined||dis==""||dis==0||dis=="0")
	{
		return {distance:0,res:true};
	}
	var lat1 = latitude || 0;
	var lng1 = longitude || 0;
	var lat2 = clat || 0;
	var lng2 = clon || 0;
	var rad1 = lat1 * Math.PI / 180.0;
	var rad2 = lat2 * Math.PI / 180.0;
	var a = rad1 - rad2;
	var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	var r = 6378137;
	var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
	if(parseInt(distance)>parseInt(dis))
	{
		return {distance:parseInt(distance),res:false};
	}else
	{
		return {distance:parseInt(distance),res:true};
	}
}
export const setSystemGrey = function(endTime)
{
	let nowTime = new Date().getTime();
	let overTime = new Date(endTime).getTime();
	if (nowTime < overTime) {
		$("html").css({
			'-webkit-filter': 'grayscale(100%)',
			'-moz-filter': 'grayscale(100%)',
			'-ms-filter': 'grayscale(100%)',
			'-o-filter': 'grayscale(100%)',
			'filter': 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)',
			'_filter': 'none' });
		window.localStorage.setItem("GREY_END_TIME",endTime);
	}
}
export const RSAEncrypt = function(str)
{
	let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz1zqQHtHvKczHh58ePiRNgOyiHEx6lZDPlvwBTaHmkNlQyyJ06SIlMU1pmGKxILjT7n06nxG7LlFVUN5MkW/jwF39/+drkHM5B0kh+hPQygFjRq81yxvLwolt+Vq7h+CTU0Z1wkFABcTeQQldZkJlTpyx0c3+jq0o47wIFjq5fwIDAQAB";
	let jse = new JSEncrypt();
	jse.setPrivateKey(publicKey)
	return jse.encrypt(str);
}

/**
 * 转换Message的Url
 * @param view
 * @param recordId
 * @returns {string}
 */
export const convertMessageUrl = function(view,recordId)
{
	let  protocol = window.location.protocol;
	let  host = window.location.host;
	let  port = window.location.port==='80'?'':window.location.port;
	if(view==="NEWS")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/news/details?newsId="+recordId;
	}else if(view==="EMAIL")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/email/details?emailId="+recordId;
	}else if(view==="NOTICE")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/notice/details?noticeId="+recordId;
	}else if(view==="DIARY")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/diary/details?diaryId="+recordId;
	}else if(view==="TASK")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/task/details?taskId="+recordId;
	}else if(view==="DUTY")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/duty/details?recordId="+recordId;
	}else if(view==="WORK_PLAN")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/workplan/details?planId="+recordId;
	}else if(view==="HR_SALARY")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/hr/salary/details?recordId="+recordId;
	}else if(view==="HR_CONTRACT")
    {
        window.location.href = protocol+"//"+host+ port+"/#/app/hr/contract/details?contractId="+recordId;
    }else if(view==="HR_LICENCE")
    {
        window.location.href = protocol+"//"+host+ port+"/#/app/hr/licence/details?licenceId="+recordId;
    }else if(view==="VOTE")
	{
		window.location.href = protocol+"//"+host+ port+"/#/app/vote/details?voteId="+recordId;
	}else if(view==="BPM_APPROVED"||view==="BPM_CHANGE_USER")
	{
		let l = recordId.length/3;
		let runId = recordId.substring(0,l);
		let stepRunId = recordId.substring(l,l*2);
		let flowId = recordId.substring(l*2,l*3);
		window.location.href = protocol+"//"+host+ port+"/#/bpm/handle/dowork?runId="+runId+"&stepRunId="+stepRunId+"&flowId="+flowId;
	}else if(view==="DOC_APPROVED"||view==="DOC_CHANGE_USER")
	{
		let l = recordId.length/3;
		let runId = recordId.substring(0,l);
		let stepRunId = recordId.substring(l,l*2);
		let flowId = recordId.substring(l*2,l*3);
		window.location.href = protocol+"//"+host+ port+"/#/doc/handle/dowork?runId="+runId+"&stepRunId="+stepRunId+"&flowId="+flowId;
	}else if(view==="BPM_CREATE"||view==="BPM_JOIN"||view==="BPM_REMINDER")
	{
		window.location.href = protocol+"//"+host+ port+"/#/bpm/handle/read?runId="+recordId;
	}else if(view==="BPM_SEND_USER"){
		let l = recordId.length/2;
		let runId = recordId.substring(0,l);
		let sendToId = recordId.substring(l,l*2);
		window.location.href = protocol+"//"+host+ port+"/#/bpm/handle/read?runId="+runId+"&sendToId="+sendToId;
	}else if(view==="DOC_CREATE"||view==="DOC_JOIN"||view==="DOC_REMINDER")
	{
		window.location.href = protocol+"//"+host+ port+"/#/doc/handle/read?runId="+recordId;
	}else if(view==="DOC_SEND_USER"){
		let l = recordId.length/2;
		let runId = recordId.substring(0,l);
		let sendToId = recordId.substring(l,l*2);
		window.location.href = protocol+"//"+host+ port+"/#/doc/handle/read?runId="+runId+"&sendToId="+sendToId;
	}
}
